﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;

namespace HWCDNLogAnalysis.Model
{
    /// <summary>
    /// 华为云CDN访问日志
    /// </summary>
    /// 华为云CDN日志格式介绍 https://support.huaweicloud.com/usermanual-cdn/zh-cn_topic_0073337424.html
    /// date: 2022-07-20
    public class BrowseLog
    {
        public BrowseLog() { this.Log = ""; this.Id = 0; }
        public BrowseLog(int id, string log)
        {
            Id = id;
            Log = log;
            // [05/Feb/2018:07:54:52 +0800] x.x.x.x 1 "-" "HTTP/1.1" "GET" "www.test.com" "/test/1234.apk" 206 720 HIT "Mozilla/5.0 (Linux; U; Android 6.0; zh-cn; EVA-AL10 Build/HUAWEIEVA-AL10) AppleWebKit/533.1 (KHTML，like Gecko) Mobile Safari/533.1" "bytes=-256"
            // 日志生成时间 访问IP地址 响应时间(单位ms) Referer信息 HTTP协议标识 HTTP请求方式 CDN加速域名 请求路径 HTTP状态码 返回字节数大小 缓存命中状态 User-Agent信息 Range信息
           var dic=GetDictionary(ref log); 
            var arr = log.Split(' ');
            if (arr.Length> 12 && dic.Count>0)
            {
                TimeLocal =(arr[0]+" "+arr[1]).Replace("[", "").Replace("]", "");

                RemoteAddr = arr[2];
                HttpResponseTime = arr[3];
                HttpReferer = dic[arr[4]];
                Request = dic[arr[5]];
                Action = dic[arr[6]];
                CDNUri = dic[arr[7]];
                Uri = dic[arr[8]];
                Status = arr[9];
                BodyBytesSent = arr[10];
                CDNHit = arr[11];
                HttpUserAgent = dic[arr[12]];
                HttpRange = dic[arr[13]];

            }
        }
        private Dictionary<string, string> GetDictionary(ref string input)
        {
            Dictionary<string, string> dict = new Dictionary<string, string>();
            var _regex = new Regex("\"([^\"]*)\"", RegexOptions.IgnoreCase);
            var _machs=_regex.Matches(input);
            if (_machs.Count > 0)
            {
                var i = 0;
                foreach (Match _mach in _machs)
                {
                    i++;
                    dict.Add($"a{i}", _mach.Value.Replace("\"",""));
                    input = input.Replace(_mach.Value, $"a{i}");
                }
            }
            return dict;
        }
        public int Id { set; get; }
        /// <summary>
        /// 日志字符串
        /// </summary>
        public string Log { set; get; }
        /// <summary>
        /// 客户端地址
        /// </summary>
        public string? RemoteAddr { set; get; }
    
        /// <summary>
        /// 访问时间和时区
        /// </summary>
        public string? TimeLocal { set; get; }
        /// <summary>
        /// 访问时间
        /// </summary>
        public string? VisitTime
        {
            get
            {
                if (string.IsNullOrEmpty(TimeLocal))
                {
                    return null;
                }
                //05/Feb/2018:07:54:52
                var _time = TimeLocal.Split(' ')[0];
                var _time2 = ChkMonth(_time);
                return _time2==""?_time:DateTime.ParseExact(_time2, "dd/MM/yyyy:HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture).ToString("G");
            }
        }
        /// <summary>
        /// 替换英文的缩小月
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        private string ChkMonth(string time)
        {
            var _enmonth = "Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec".Split('|');
            for (int i = 0; i < _enmonth.Length; i++)
            {
                if (time.Contains(_enmonth[i]))
                {
                    return time.Replace(_enmonth[i],(i+1).ToString().PadLeft(2,'0'));
                }
            }
            return "";
        }
        /// <summary>
        /// 访问时区
        /// </summary>
        public string? TimeZone
        {
            get
            {
                if (string.IsNullOrEmpty(TimeLocal))
                {
                    return string.Empty;
                }
                return TimeLocal.Split(' ')[1];
            }
        }
        /// <summary>
        /// 请求的URI和HTTP协议
        /// </summary>
        public string? Request { set; get; }
        /// <summary>
        /// 请求方式
        /// </summary>
        public string? Action { set; get; }
        /// <summary>
        /// 加速域名
        /// </summary>
        public string? CDNUri { set; get; }
        /// <summary>
        /// 请求地址
        /// </summary>
        public string? Uri { set; get; }
        /// <summary>
        /// HTTP请求状态
        /// </summary>
        public string? Status { set; get; }
        /// <summary>
        /// 发送给客户端文件内容大小
        /// </summary>
        public string? BodyBytesSent { set; get; }
        /// <summary>
        /// url跳转来源
        /// </summary>
        public string? HttpReferer { set; get; }
        /// <summary>
        /// 用户终端浏览器等信息
        /// </summary>
        public string? HttpUserAgent { set; get; }
        /// <summary>
        ///  响应时间(单位ms) 
        /// </summary>
        public string? HttpResponseTime { set; get; }

        /// <summary>
        /// 缓存命中状态（hit/miss）
        /// </summary>
        public string? CDNHit { set; get; }
        /// <summary>
        /// Range信息
        /// </summary>
        public string? HttpRange { set; get; }
    }
}
